import React from 'react'
import { Table,Icon,Modal,Popconfirm,Form,Input,Row,Col,DatePicker,Button,Message,Select} from 'antd';
const FormItem = Form.Item;
const { TextArea } = Input;
const Option = Select.Option;
import api from '../../../api/advRelease';
import {uuid} from "../../../utils";

const { RangePicker } = DatePicker;
import moment from 'moment';

import PanelBox from '../../../components/PanelBox';
import {jsonToTree} from '../../../utils/tools'

import '../../../style/antd-theme.less';

export default class TablePage extends React.Component {
  state = {
    userSession:'',
    data: [],
    pagination: {
      pageSize:20,
      pageNum:1,
    },
    loading: false, 
    rowRecord:'',
    operate:{
      isOpen:false,
    
    }
  };
  columns = [{
    title: '广告标题',
    dataIndex: 'title',
  },{
    title: '播放类型',
    dataIndex: 'reward',
    width: '10%',
    render:(text, record, index) =>  {
      switch(record.reward){
        case 1:
          return '轮播';
        case 2:
         return '精准';
        default:
          return '未知';
      }
    },
  },{
    title: '总天数 ',
    dataIndex: 'allDays',
    width: '10%',
  },{
    title: '支付金额',
    dataIndex: 'payMo',
    width: '10%',
  },{
    title: '接受状态',
    dataIndex: 'state',
    width: '11%',
    render:(text, record, index) =>  {
      switch(record.state){
        case 1:
          return '待接受';
        case 2:
         return '通过';
        case 3:
         return '拒绝';
        case 0:
         return '临时';
        default:
          return '未知';
      }
    },
  },{
    title: '创建时间',
    dataIndex: 'createDate',
    width: '15%',
  }, {
    title: '操作',
    key: 'action',
    width: '15%',
    render: (text, record) => {
      switch(record.state){
        case 1:
          return (<span>
        <a href="javascript:void(0)" onClick={this.operate.openModal.bind(this, record)}>通过</a>
        <span className="ant-divider" />
        <Popconfirm title="您是否要拒绝该广告?" onConfirm={this.operate.handleSubmit.bind(this, {id:record.id,state :3})}  okText="是" cancelText="否">
          <a href="javascript:void(0)">拒绝</a>
        </Popconfirm>
      </span>);
        case 2:
         return '已通过';
        case 3:
         return '已拒绝';
        case 0:
         return '临时';
        default:
          return '未知';
      }
    } 
  }];

  handleTableChange = (pagination, filters, sorter) => {
    pagination.pageNum=pagination.current;
    this.setState({pagination});
   
    this.fetch({...pagination});
  }
  fetch = (params) => {
    this.setState({ loading: true });
    params['queryType']=3;
    api.get('/advRelease/getAll', { params}).then((data) => {
      const _data = data.data.list;
      const pagination = { ...this.state.pagination };
      pagination.total = data.data.total;
      this.setState({
        loading: false,
        data: _data,
        pagination,
      });
    });
  }

  componentDidMount = () =>{
    let user =this.props.profile.user;
    this.setState({
      userSession:user
      });
    this.fetch({ ...this.state.pagination });

  }

  close = () => {
    this.setState({
      isOpenModal: false,
      clearForm: true,
    });
  }
  refeshData = () => {
    this.fetch({ ...this.state.pagination });
  }

  initChildrenParams = (params) => {
    this.resetFields = params.resetFields;
  }
  operate={
    openModal:(record, event)=>{
      const operate=this.state.operate;
      operate.recordId=record.id;
      operate.isOpen=true;
      this.setState({operate});
    },
    closeModal:()=>{
      const operate=this.state.operate;
      operate.isOpen=false;
      this.setState({operate});
    },
    handleSubmit:(params) => {
      api.post('/advScreenInfo/exam/add',params ).then((data) => {
        const result = data.data;
        if(result.code == 0){
          Message.success('操作成功！');
          this.operate.closeModal();
          this.fetch({ ...this.state.pagination });
         }else{
          Message.error(result.message);
         }
      });
    },
  }
  rowDetail=(record)=>{
    let pho='';
    if(record.photos){
        let phos=JSON.parse(record.photos);
        pho = <Col span={3}><a href={phos[0]} target='_blank' title="点击查看原图"><img src={phos[0]} width="100px" height="100px"/></a></Col>
    }
    let date='';
    if(record.startDate  || record.endDate){
      date = <Col span={8}>起止时间：{record.startDate } - {record.endDate }</Col>
    }
    let reward='';
    let voice='';
    if(record.reward == 2){
      if(record.voice){
        let voices=JSON.parse(record.voice);
        voice=<Col >音频：<a href={voices[0]} title={voices[0]} target='_blank'>{voices[0]}</a></Col>
      }
      let sex='未知';
      if(record.sex==0){
        sex="不限制";
      }else if(record.sex==1){
        sex="男";
      }else if(record.sex==2){
        sex="女";
      }
      reward=<Col><Col span={3}>最小年龄：{record.minAge}</Col>
      <Col span={3}>最大年龄：{record.maxAge}</Col>
      <Col span={3}>性别： {sex} </Col>
      </Col>
    }
    let row= 
   <div> <Row style={{lineHeight:'100px'}}>
        {pho}
        <Col span={3}>套餐：{record.combName }</Col>
        <Col span={3}>设备数：{record.allHardNum }</Col>
        {date}{reward}
    </Row>{voice}</div>;
    
    return row;
  }

  render() {
    
    return (
      <div>
        <SearchForm searchCostState={this.state} goSearch={this.handleTableChange}/>
        <PanelBox>
          <Table columns={this.columns}  dataSource={this.state.data}  pagination={this.state.pagination}
            loading={this.state.loading}  onChange={this.handleTableChange}  rowKey='id'
            expandedRowRender={this.rowDetail}
          />
        </PanelBox>
        <Modal
          title="操作"
          visible={this.state.operate.isOpen}
          onCancel={this.operate.closeModal}
          wrapClassName="vertical-center-modal"
          footer={null}
          >
         <OperateForm operate={this.operate} record={this.state.operate}/>
        </Modal>
      </div>
    );
  }
}
    class OperateForms extends React.Component {
      
      goOperate = (e) => {
        let params=this.props.form.getFieldsValue().operate;
        if (typeof(params.startDate) != 'undefined') {
          params.startDate = moment(params.startDate).format("YYYY-MM-DD");
          params.state =2;//通过
          const _this = this.props.operate;
          _this.handleSubmit(params);
        }
        
     
      }

      srearchStyle = {
        labelCol: { span: 6 },
        wrapperCol: { span: 10 },
      };
      tailFormItemLayoutStyle = {
        wrapperCol: {
          xs: {
            span: 14,
            offset: 0,
          },
          sm: {
            span: 14,
            offset: 6,
          },
        },
      };
     
      render() {
        const { getFieldDecorator } = this.props.form;
        const record = this.props.record;
        const _this = this.props.operate;
        const formItemLayout = this.srearchStyle;
        const tailFormItemLayout = this.tailFormItemLayoutStyle;
        const operate = {
          name: "id",
          name: "startDate",
          name: "remarks",
        };
        return <Form onSubmit={this.goOperate} >
          {getFieldDecorator('operate.id',{initialValue:record ? record.recordId : ''})(
              <Input type="hidden" />
            )}
           

          <FormItem {...formItemLayout} label="分配开始日期"  hasFeedback>
            {getFieldDecorator('operate.startDate', {
              rules: [{ required: true, message: '不能为空!' }],
              })(
                <DatePicker/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="备注">
            {getFieldDecorator('operate.remarks')(
              <TextArea/>
            )}
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button type="primary"  style={{marginRight:'10px'}} htmlType="submit"   >确定</Button>
            <Button  onClick={_this.closeModal}>取消</Button>
          </FormItem> 
        </Form>
      }
    }
    const OperateForm = Form.create({})(OperateForms);

    class SearchsForm extends React.Component {
      // 开始搜索
      goSearch = (e) => {
        let params=this.props.form.getFieldsValue().search;
        let _this=this.props;
        params.pageSize=_this.searchCostState.pagination.pageSize;
        params.pageNum =1;
        params.current =1;
        _this.goSearch(params);
     
      }

      srearchStyle = {
        labelCol: { span: 8},
        wrapperCol: { span: 14 },
      };
     
      render() {
        const { getFieldDecorator } = this.props.form;
        const {create } = this.props;
        const formItemLayout = this.srearchStyle;
        const search = {
          name: "title",
        };
        return <Form onSubmit={this.goSearch} layout="inline" style={{marginBottom:'10px'}}>
          <FormItem {...formItemLayout} label="广告标题" style={{marginRight:0,marginBottom:'10px'}}>
            {getFieldDecorator('search.title')(
              <Input type="text" placeholder="搜索的广告标题"/>
            )}
          </FormItem>
          <FormItem>
            <Button type="primary" icon="search" htmlType="submit">搜索</Button>
          </FormItem> 
        </Form>
      }
    }
    const SearchForm = Form.create({})(SearchsForm);